#!/bin/bash
set -e
cur_pwd=$(cd $(dirname $0);pwd)
function help() {
    echo
    echo "Usage:"
    echo "sh new_third_party_repo.sh --old_repo_url {old_repo_url} --old_repo_branch  {old_repo_branch} --new_repo_url {new_repo_url} --new_repo_adm_pw {username:password} [options]"
    echo "sh new_third_party_repo.sh --old_repo_url https://github.com/xxxx --old_repo_branch master --old_repo_adm_pw username1:password1 --new_repo_url https://gitee.com/xxxx --new_repo_adm_pw username2:password2"
    echo 
    echo "options"
    echo "--old_repo_adm_pw  old_repo username and password if it's necessary"
}
while [ $# -gt 0 ];do
    case "$1" in
        -h|--help)
            help
            exit 0
            ;;
        --old_repo_url)
            old_repo_url=$2
            shift 2
            ;;
        --old_repo_branch)
            old_repo_branch=$2
            shift 2
            ;;
        --old_repo_adm_pw)
            old_repo_adm_pw=$2
            shift 2
            ;;
        --new_repo_url)
            new_repo_url=$2
            shift 2
            ;;
        --new_repo_adm_pw)
            new_repo_adm_pw=$2
            shift 2
            ;;
        *)
            echo "error parm $1"
            exit 1
    esac
done
            
if [ -n "$old_repo_adm_pw" ];then
    old_repo_url=${old_repo_url#https:\/\/*}
    old_repo_url="https://$old_repo_adm_pw@${old_repo_url}"
fi
if [ -n "${new_repo_adm_pw}" ];then
    new_repo_url=${new_repo_url#https:\/\/*}
    new_repo_url="https://${new_repo_adm_pw}@${new_repo_url}"
fi
old_repo_dir=${old_repo_url##*/}
cd ${cur_pwd}
if [ -d ${old_repo_dir} ];then
    rm -rf ${old_repo_dir:-/tmp/A_-_B_-_C}
fi
git init --bare ${old_repo_dir}.git
if [ $? -gt 0 ];then echo 'error:init failed';fi
cd ${old_repo_dir}.git
git fetch -f  ${old_repo_url}  ${old_repo_branch}:${old_repo_branch}
if [ $? -gt 0 ];then echo 'error:fetch from source failed';fi
#下载大文件
git lfs fetch --all ${old_repo_url}
if [ $? -gt 0 ];then echo 'error:fetch lfs from source failed';fi
git  push --force ${new_repo_url} ${old_repo_branch}:master
if [ $? -gt 0 ];then echo 'error:push to target failed';fi
# 备份来源refs信息到refs/tag
source_tag_name=`echo ${old_repo_url}|sed 's#.*://##g;s#.*@##g'`
date_info=`date '+%Y-%m-%d_%H_%M_%S'`
git  push  ${new_repo_url} ${old_repo_branch}:refs/tags/${date_info}/${source_tag_name}/${old_repo_branch}
if [ $? -gt 0 ];then echo 'error:back tag info failed';fi

cd $cur_pwd
rm -rf ${old_repo_dir:-/tmp/A_-_B_-_C}
if [ $? -gt 0 ];then echo 'error:rm old_repo_dir failed';fi

